package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.behavior.mapper.ApLikesBehaviorMapper;
import com.usian.behavior.service.ApLikesBehaviorService;
import com.usian.behavior.service.BehaviorEntryService;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.behavior.dtos.LikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApLikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl extends BaseServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {
    @Autowired
    private BehaviorEntryService entryService;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        if (dto == null || dto.getArticleId() == null || dto.getOperation() == null) return paramError;
        if (dto.getOperation() != 0 && dto.getOperation() != 1) return paramError;
        Integer userId = ThreadLocalUtils.getUser();
        if (userId == null) return needLogin;
        ApBehaviorEntry behaviorEntry = entryService.findByUserIdOrEquipmentId(userId);
        ApLikesBehavior likesBehavior = getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getArticleId, dto.getArticleId()).eq(ApLikesBehavior::getEntryId, behaviorEntry.getId()));
        if (likesBehavior == null) {
            if (dto.getOperation() == 0) {
                ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
                apLikesBehavior.setEntryId(behaviorEntry.getId());
                apLikesBehavior.setOperation(dto.getOperation());
                apLikesBehavior.setArticleId(dto.getArticleId());
                apLikesBehavior.setCreatedTime(new Date());
                apLikesBehavior.setType(dto.getType() == null ? 0 : dto.getType());
                save(apLikesBehavior);
            }else {
                System.out.println("没有点赞记录");
            }
        }else {
            likesBehavior.setOperation(dto.getOperation());
            updateById(likesBehavior);
        }
        return okResult;
    }

    @Override
    public ApLikesBehavior getLike(Long articleId, Integer entryId) {
        if (articleId!=null && entryId!=null)return getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getArticleId,articleId).eq(ApLikesBehavior::getEntryId,entryId));
        return null;
    }


}
